package com.yksj.healthtalk.wallet;

import java.util.ArrayList;
import java.util.Calendar;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import org.handmark.pulltorefresh.library.PullToRefreshListView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.recharge.ChoiseDateActivity;
import com.yksj.healthtalk.utils.TimeUtil;

/**
 * 账单
 * @author Administrator
 */
@SuppressLint("ValidFragment")
public class MyBillFragment extends Fragment implements OnClickListener, OnRefreshListener<ListView>{
	
	private PullToRefreshListView mPullToRefreshListView;
	private BillAdapter adapter;
	private ListView mListView;
	private int pageSize = 20;
	private int pageNum = 1;
	private ArrayList<BillEntity> billEntities = new ArrayList<BillEntity>();
	private String type;
	private Button mCalender;
	private TextView nowTime;
	private String date;
	public MyBillFragment(String type){
		this.type = type;
		pageNum = 1;
	}
	
	public MyBillFragment(){
		pageNum = 1;
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.my_bill_layout, null);
		initWidget(v);
		initDate(v);
		return v;
	}

	private void initDate(View v) {
		if (type != null) {
			if (pageNum ==1) {//防止再次点击标题访问网络
				doHttp(type,TimeUtil.getMoneyTime().substring(0,4)+"");
				mPullToRefreshListView.setRefreshing();
			}
		}
		Calendar cal=Calendar.getInstance();    
		int y=cal.get(Calendar.YEAR); 
		nowTime.setText(y+"");
	}

	private void initWidget(View v) {
		mCalender = (Button)v.findViewById(R.id.c);
		nowTime = (TextView)v.findViewById(R.id.day);
		mPullToRefreshListView = (PullToRefreshListView) v.findViewById(R.id.hall);
		mPullToRefreshListView.setOnRefreshListener(this);
		mListView = mPullToRefreshListView.getRefreshableView();
		mListView.addFooterView(View.inflate(getActivity(), R.layout.list_line_layout, null));
		adapter = new BillAdapter(billEntities);
		mListView.setAdapter(adapter);
		mCalender.setOnClickListener(this);
	}
	
	class BillAdapter extends BaseAdapter{
		LayoutInflater inflater;
		ViewHolder holder;
		private ArrayList<BillEntity> billEntities;
		public BillAdapter(ArrayList<BillEntity> billEntities) {
			inflater  = LayoutInflater.from(getActivity());
			this.billEntities = billEntities;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return billEntities.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.bill_item, null);
				holder = new ViewHolder();
				holder.mBalance = (TextView) convertView.findViewById(R.id.balance);
				holder.mBillName = (TextView) convertView.findViewById(R.id.bill_name);
				holder.mBillTime = (TextView) convertView.findViewById(R.id.bill_time);
				holder.	mMoney = (TextView) convertView.findViewById(R.id.money);	
				convertView.setTag(holder);
			}else {
				holder = (ViewHolder) convertView.getTag();
			}
				holder.mBalance.setText(billEntities.get(position).getBALANCE_AFTER());
				holder.mBillName.setText(billEntities.get(position).getCHANGE_TYPE());
				holder.mBillTime.setText(billEntities.get(position).getCHANGE_TIME());
				holder.mMoney.setText(billEntities.get(position).getCHANGE_VALUE());
			return convertView;
		}
	}
	
	class ViewHolder{
		private TextView mBillName;
		private TextView mBillTime;
		private TextView mMoney;
		private TextView mBalance;
	}
	
	/**
	 * 客户ID：CUSTOMERID
		流水类型:TYPE
  ----"" 进出流水 默认值
  ----"IN" 进账流水
  ----"OUT" 出账流水
		时间:TIME  可为空
		页码:PAGENUM  默认为1
		页数:PAGECOUNT 默认20
	 * @param pageSize
	 * @param pagePage
	 */
	public void doHttp(String type,String time){
		RequestParams params = new RequestParams();
		params.put("CUSTOMERID", SmartFoxClient.getLoginUserId());
		params.put("TYPE", type);
		params.put("PAGECOUNT", pageSize+"");
		params.put("PAGENUM", pageNum+"");
		params.put("TIME", time);
		params.put("VERSION", "4");
		HttpRestClient.doHttpBalanceChange(params, new JsonsfHttpResponseHandler(getActivity()){
			@Override
			public void onFinish() {
				mPullToRefreshListView.onRefreshComplete();
				super.onFinish();
			}
			@Override
			public void onSuccess(int statusCode,
					com.alibaba.fastjson.JSONObject response) {
				try {
					if (pageNum == 1) {
						billEntities.clear();
					}
					pageNum++;
					JSONArray mInfoArr = response.getJSONArray("CHANGE_INFO");
					for (int i = 0; i < mInfoArr.size(); i++) {
						BillEntity entity = new BillEntity();
						entity.setBALANCE_AFTER(mInfoArr.getJSONObject(i).getString("BALANCE_AFTER"));
						entity.setCHANGE_TYPE(mInfoArr.getJSONObject(i).getString("CHANGE_TYPE"));
						entity.setCHANGE_TIME(mInfoArr.getJSONObject(i).getString("CHANGE_TIME"));
						entity.setCHANGE_VALUE(mInfoArr.getJSONObject(i).getString("CHANGE_VALUE"));
						billEntities.add(entity);
					}
					adapter.notifyDataSetChanged();
				} catch (Exception e) {
					if (response.containsKey("INFO")) {
						SingleBtnFragmentDialog.showDefault(getFragmentManager(), response.getString("INFO"));
					}
					e.printStackTrace();
				}
				super.onSuccess(statusCode, response);
			}
		});
	}
	
	class BillEntity {
		String CHANGE_TYPE;
		String CHANGE_TIME;
		String CHANGE_VALUE;
		String BALANCE_AFTER;
		
		public String getCHANGE_TYPE() {
			return CHANGE_TYPE;
		}
		public void setCHANGE_TYPE(String cHANGE_TYPE) {
			CHANGE_TYPE = cHANGE_TYPE;
		}
		public String getCHANGE_TIME() {
			return CHANGE_TIME;
		}
		public void setCHANGE_TIME(String cHANGE_TIME) {
			CHANGE_TIME = cHANGE_TIME;
		}
		public String getCHANGE_VALUE() {
			return CHANGE_VALUE;
		}
		public void setCHANGE_VALUE(String cHANGE_VALUE) {
			CHANGE_VALUE = cHANGE_VALUE;
		}
		public String getBALANCE_AFTER() {
			return BALANCE_AFTER;
		}
		public void setBALANCE_AFTER(String bALANCE_AFTER) {
			BALANCE_AFTER = bALANCE_AFTER;
		}
		
		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.c:
			Intent intent=new Intent(getActivity(),ChoiseDateActivity.class);
			if(nowTime.getText().toString().length()<5){
				intent.putExtra("date", TimeUtil.getMoneyTime());
			}else{
				intent.putExtra("date", nowTime.getText().toString());
			}
			startActivityForResult(intent,0);
			break;
		}
	}
	
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode!=getActivity().RESULT_OK || data==null)return;
		switch (requestCode) {
		case 0:
			Bundle extras = data.getExtras();
			if(extras.containsKey("all")){
				date = "";
				Calendar cal=Calendar.getInstance();    
				int y=cal.get(Calendar.YEAR); 
				nowTime.setText(y+"");
				}else{
					if(extras.containsKey("nothing"))return;
					String string = extras.getString("date");
					String string1 = extras.getString("year");
					nowTime.setText(string1+"-"+string);
					date=string1+string;
			}
			pageNum = 1;
			doHttp(type,date);
			mPullToRefreshListView.setRefreshing();
			break;
		}
	}
	@Override
	public void onRefresh(PullToRefreshBase<ListView> refreshView) {
		doHttp(type,TimeUtil.getMoneyTime().substring(0,4)+"");
	}
}
